package cn.edkuir.product.service.impl;

import cn.edkuir.product.entity.AttrEntity;
import cn.edkuir.product.service.AttrService;
import cn.edkuir.product.vo.AttrGroupWithAttrsVo;
import cn.edkuir.product.vo.SkuItemVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edkuir.common.utils.PageUtils;
import cn.edkuir.common.utils.Query;

import cn.edkuir.product.dao.AttrGroupDao;
import cn.edkuir.product.entity.AttrGroupEntity;
import cn.edkuir.product.service.AttrGroupService;
import org.springframework.util.StringUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Autowired
    private AttrService attrService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            wrapper.and((obj)->{
                obj.eq("attr_group_id", key).or().like("attr_group_name", key);
            });
        }
        if(catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        return new PageUtils(this.page(
                new Query<AttrGroupEntity>().getPage(params),
                wrapper));
    }

    //根据分类id查出所有分组以及分组的具体属性
    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        //1.查询所有分组
        List<AttrGroupEntity> groupEntities = this.list(
                new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId)
        );

        //2.查出所有属性
        return groupEntities.stream().map(item->{
            AttrGroupWithAttrsVo vo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(item, vo);
            List<AttrEntity> attrEntities = attrService.getRelationAttr(item.getAttrGroupId());
            vo.setAttrs(attrEntities);
            return vo;
        }).collect(Collectors.toList());
    }



    //根据分类id和spuId查出所有分组名字及分组对应的所有基本属性
    @Override
    public List<SkuItemVo.SpuItemAttrGroupVo> getGroupNameAndAttrs(Long catalogId, Long spuId) {
        return baseMapper.selectGroupNameAndAttrsBySpuIdAndCatalogId(spuId, catalogId);
    }


}